#!/bin/bash
in="TagReference.wiki"
out="TagReference.tmp"

# Function to generate the table of tags
function writeTable() {
  # For each Tag*.wiki file that has a tagname in the summary
  for file in `grep -l "#summary.*@\w*" Tag*.wiki`; do
    # Extract the tag name
    tag=`grep "^#summary" $file | sed -e "s/.*\(@\w\+\).*/\1/g"`
    # Extract the first sentence of the description
    comment=`(tr '\n' ' ' | sed -e "s/.*==\s*Description\s*==\s*\([^\.=]*\).*/\1/") < $file`
    # Write out the tag-description
    echo "|| [${file/.wiki/} $tag] || $comment ||" >> $out
  done
}

# Make sure tmp file is gone
\rm -f $out

# Redirect $in to stdin
exec < $in

# Flag for "Have we written the table yet?"
wroteit=0

# For each line in input file ...
while read line; do
  if [ "${line/*||*||*/rEMOVE}" != "rEMOVE" ]; then
    # Not row in the table - write it to $out
    echo $line >> $out
  elif [ $wroteit == 0 ]; then
    # Write out our contents table
    writeTable
    # Mark that we've written it
    wroteit=1
  fi
done

# Replace the file
mv $out $in
